﻿
Partial Class private_secure_members_manage_Default
    Inherits System.Web.UI.Page
    Dim u As MembershipUser
    Dim personId As Int32

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim getpersonid As New GetPersonIdFromUserId()
        u = Membership.GetUser(User.Identity.Name)
        personId = getpersonid.GetPersonId(CType(u.ProviderUserKey, Guid))

        If Not Page.IsPostBack Then
            If Not Session("EntityID") Is Nothing Then
                ddlEntityList.SelectedValue = CStr(Session("EntityID"))
            End If
        End If
    End Sub

    Protected Sub ObjectDataSource1_Selecting(sender As Object, e As System.Web.UI.WebControls.ObjectDataSourceSelectingEventArgs) Handles ObjectDataSource1.Selecting
        e.InputParameters("PersonId") = personId
    End Sub

    Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
        Dim unvalid As String = String.Empty

        If FileUpload1.HasFile Then
            Try
                ' upload.SaveAs(HttpContext.Current.Server.MapPath(lblPath.Text) + c)
                FileUpload1.SaveAs(HttpContext.Current.Server.MapPath("~/uploads/") & FileUpload1.FileName)
                lblUploadInfo.Text = "File name: " & _
                   FileUpload1.PostedFile.FileName & "<br>" & _
                   "File Size: " & _
                   FileUpload1.PostedFile.ContentLength & " kb<br>" & _
                   "Content type: " & _
                   FileUpload1.PostedFile.ContentType
            Catch ex As Exception
                lblUploadInfo.Text = "ERROR: " & ex.Message.ToString()
            End Try
            lblUploadInfo.Text = "You have not specified a file."
            Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(HttpContext.Current.Server.MapPath("~/uploads/") & FileUpload1.FileName)
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.SetDelimiters(",")
                Dim currentRow As String()
                Dim rownumber As Integer = 0
                While Not MyReader.EndOfData
                    rownumber = rownumber + 1
                    Try
                        currentRow = MyReader.ReadFields()
                        Dim currentField As String
                        For Each currentField In currentRow
                            If Not CheckEmail(currentField) Then
                                MsgBox("Line number " & rownumber & " contain invalid email" & ", address " & currentField & " was not formed as valid email address.")
                                'unvalid = unvalid + currentField + "</br>"
                            Else
                                If CDbl(ddlEntityList.SelectedValue) = 0 Then
                                    Label1.Text = "Please select item from list."
                                Else
                                    Label1.Text = String.Empty
                                    u = Membership.GetUser(User.Identity.Name)

                                    Dim newutility As New Utility
                                    Dim token As Guid = Guid.NewGuid()

                                    Dim sendersPersonidTA As New LogginsLogDSTableAdapters.PersonTableAdapter()
                                    Dim sendersPersonid As Integer
                                    Try
                                        sendersPersonid = sendersPersonidTA.GetData(CType(u.ProviderUserKey, Guid?)).FirstOrDefault().Id
                                    Catch ex As Exception
                                        Throw ex
                                    End Try

                                    Dim virtualurl As String = ("http://" + HttpContext.Current.Request.Url.Authority.ToString() + "/" + _
                                        HttpContext.Current.Request.Url.Segments(1).ToString() + "Account/AssociateValidate.aspx?invitation=").Replace("Account/Account/", "Account/")

                                    Dim strMailFrom As String = ConfigurationManager.AppSettings("smtpmailfrom").ToString()
                                    Dim strMailTo As String = ConfigurationManager.AppSettings("accountapprovalemail").ToString()

                                    Dim sendemail As New SendEmailViaGoogle()

                                    Dim strSubject As String = "Your Associate Login"
                                    Dim strMessage As String = "A login has been requested for you by your colleague to use our site. To use this login as an Associate please click the link supplied in this email. Please use the link before it expires in 7 days. Please note that it can only be used one time."

                                    'Make sure the email address is not empty
                                    If currentField.Length > 0 Then

                                        Dim NewPersonAssociateRequestTA As New LogginsLogDSTableAdapters.usp_PersonAssociateRequestTableAdapter()

                                        Dim b As Integer
                                        Try

                                            '1- Write the request
                                            b = NewPersonAssociateRequestTA.Insert(sendersPersonid, Convert.ToInt32(Me.ddlEntityList.SelectedValue), currentField, token, False, DateTime.Now, 7, Nothing, True)

                                            '2- Sending email to the new user
                                            sendemail.SendEmail(strMailFrom, currentField, strSubject, strMessage + " Please click here. " + virtualurl + token.ToString())

                                            strMessage = "User: " + u.UserName + Environment.NewLine + _
                                                                "requested for: " + currentField + Environment.NewLine + " " + strMessage + " " + virtualurl + token.ToString()

                                            '3- Sending email to the administrator
                                            sendemail.SendEmail(strMailFrom, strMailTo, strSubject, strMessage)

                                            '4- Also send an email to the person making the Request
                                            strSubject = "The login you requested " + strMailTo
                                            strMessage = "The login you requested for your Associate [" + strMailTo + "] has been sent. Please remind them that the login should be used before it expires in 7 days."
                                            strMessage = "User: " + u.UserName + Environment.NewLine + _
                                                    "requested for: " + currentField + Environment.NewLine + " " + strMessage + " " + virtualurl + token.ToString()
                                            sendemail.SendEmail(strMailFrom, strMailTo, strSubject, strMessage)

                                            Try
                                                NewGoogleCalendarEvent.CreateEvent(ConfigurationManager.AppSettings("GoogleCalendarUsername").ToString(), ConfigurationManager.AppSettings("GoogleCalendarPassword").ToString(), "Your new token is:[" & token.ToString() & "]", "test content", "1", "Test Place", "1", "1")
                                            Catch ex As Exception
                                                Throw ex
                                            End Try


                                            '5- All done, now send the user to their home page  
                                            AccUploadRegistrationSuccessModalPopupExtender.Show()

                                        Catch ex As Exception

                                        End Try
                                    Else
                                        'If Not unvalid.ToString <> String.Empty Then
                                        '    lblWrongEmailAddresses.Text = "These addresses was not well formed as valid email addresses:</br>" + unvalid
                                        'End If


                                        'lblMessage.Text = "Please Specify an Email Address"
                                    End If
                                End If


                            End If


                        Next
                    Catch ex As Microsoft.VisualBasic.
                                FileIO.MalformedLineException
                        MsgBox("Line " & ex.Message &
                        "is not valid and will be skipped.")
                    End Try
                End While
            End Using
        Else

        End If


    End Sub


    Function CheckEmail(ByVal email As String) As Boolean
        Dim validation As Boolean
        Dim pattern As String
        pattern = "^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"

        If Regex.IsMatch(email, pattern) Then
            validation = True
        Else
            validation = False
        End If
        Return validation
    End Function

    Protected Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        Response.Redirect("~/private/default.aspx")
    End Sub

    Protected Sub BtnBack_Click(sender As Object, e As EventArgs) Handles BtnBack.Click
        Response.Redirect("~/private/secure_members/manage/MyRecipients.aspx")
    End Sub
End Class
